package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author: Felix
 * Date: 2021/9/17
 * Desc: 独立访客计算
 */
public class UniqueVisitorApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        //TODO 2.设置检查点(略)
        //TODO 3.从Kafka中读取数据
        //3.1 声明消费主题以及消费者组
        String topic = "dwd_page_log";
        String groupId = "unique_visitor_app_group";

        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaSourceFunction = MyKafkaUtil.getKafkaSourceFunction(topic, groupId);

        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaDS = env.addSource(kafkaSourceFunction);

        //TODO 4.对流中数据进行类型转换
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //jsonObjDS.print(">>>>");

        //TODO 5.按照mid进行分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        //TODO 6.对分组之后的数据进行过滤（状态编程）
        SingleOutputStreamOperator<JSONObject> filterDS = keyedDS.filter(
            new RichFilterFunction<JSONObject>() {
                //注意：不能在声明状态的时候，直接对其进行初始化，因为这个时候还没有运行，获取不到RuntimeContext
                private ValueState<String> lastVisitDateState;

                private SimpleDateFormat sdf;

                @Override
                public void open(Configuration parameters) throws Exception {
                    sdf = new SimpleDateFormat("yyyyMMdd");

                    //定义状态描述器
                    ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("lastVisitDateState", String.class);
                    //设置状态中元素的ttl
                    StateTtlConfig stateTtlConfig = StateTtlConfig
                        .newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                        .build();
                    valueStateDescriptor.enableTimeToLive(stateTtlConfig);
                    lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                }

                @Override
                public boolean filter(JSONObject jsonObj) throws Exception {
                    String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");

                    if (lastPageId != null && lastPageId.length() > 0) {
                        return false;
                    }
                    //获取状态中的上次访问日期
                    String lastVisitDate = lastVisitDateState.value();

                    //获取当前页面的访问日期
                    String curVisitDate = sdf.format(new Date(jsonObj.getLong("ts")));

                    if (lastVisitDate != null && lastVisitDate.length() > 0 && lastVisitDate.equals(curVisitDate)) {
                        //今天已经访问过
                        return false;
                    } else {
                        //今天还没有访问过
                        lastVisitDateState.update(curVisitDate);
                        return true;
                    }
                }
            }
        );
        filterDS.print(">>>>>");
        //TODO 7.将过滤后的数据写回到kafka的dwm层
        filterDS
            .map(jsonObj->JSON.toJSONString(jsonObj))
            .addSink(MyKafkaUtil.getKafkaSinkFunction("dwm_unique_visitor"));

        env.execute();
    }
}
